#include "constants.h";

XfMissionChapterExecute={
	private ["_chapter_succeeded"];
	diag_log "";
	diag_log "=========================================================================";
	diag_log "                             CHAPTER 1                                   ";
	diag_log "=========================================================================";
	diag_log "";
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Starting Chapter","_last_random_reinforcement","_random_reinf_diff","_reinforcement_power"];
	DM_Mission_ArtilleryVariables = [];
	DM_Mission_Chapter_CanRun = True;
	DM_Mission_Chapter_Runs = True;
	DM_Mission_Chapter_Success = 0;
	call XfMissionChapterSetup;
	_chapter_succeeded = false;
	if (!DM_Mission_Mission_CanRun) exitWith {diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Mission canceled!"];};
	
	_random_town = DM_Chapter_Location;
	_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
	_random_town_size = _random_town select XF_MAP_LOCATION_SIZE;
	
	_vip_arrested = false;
	_vip_alive = true;
	_vip_updated = false;

	_player_detected = false;

	_enemy_initial_counts = ([_random_town_pos,_random_town_size,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
	_unique_id = 0;
	_reinforcements = 10;
	_detected_time = time;
	_initial_pos = getPos DM_VIP;
	_reinforcement_trigger = _enemy_initial_counts / 4;
	diag_log Format["(%1)[%2]: %3: %4: %5, %6",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Entering the loop",[_enemy_initial_counts,_reinforcement_trigger], Time];
	while {DM_Mission_Chapter_CanRun AND DM_Mission_Mission_CanRun} do {
		sleep 10;
		_enemy_counts = ([_random_town_pos,350,d_enemy_side] call XfMissionGetZoneSideCount) select 0;
		_vip_arrested = ["jip_vip_found",false] call XNetGetJIP;
		_vip_alive = ["jip_vip_alive",true] call XNetGetJIP;
		_vip_lead = ["jip_vip_lead",false] call XNetGetJIP;
		
		if (["jip_player_detected",false] call XNetGetJIP) then {_player_detected = true;};
		
		if (_vip_arrested && !_vip_updated && _vip_alive) then {
			DM_VIP = [DM_VIP,group DM_VIP,getPos DM_VIP,"LEAD",["","You did your best... the Commander died!","jip_vip_lead","jip_vip_alive",[getPos FLAG_BASE,[200,200],0,false]],"doStop this; removeAllWeapons this;"] call XfMissionCreateMissionUnit;
			_vip_updated = true;
			["ArrestCommander","", "","",[],"Succeeded"] call XfMissionTask;
			["LeadCommander","Lead the Commander", "Bring the commander back to the base where we will interrogate him!","",[],"Created"] call XfMissionTask;
			"The Commander is under arrest! Now bring him back!" call XfMissionMessageToAll;
		};
		
		if (_vip_lead && _vip_alive) then {
			["LeadCommander","", "","",[],"Succeeded"] call XfMissionTask;
			"You brought the Commander back! Very nice job!" call XfMissionMessageToAll;
			_chapter_succeeded = true;
			DM_Mission_Chapter_CanRun = false;
			sleep 10;
		};
		
		if (!_vip_alive) then {
			if (_vip_updated) then {
				["LeadCommander","", "","",[],"Failed"] call XfMissionTask;
			} else {
				["ArrestCommander","", "","",[],"Failed"] call XfMissionTask;
			};
			_chapter_succeeded = false;
			DM_Mission_Chapter_CanRun = false;
			sleep 10;
		};
		if (_vip_alive && !_vip_updated && ((DM_VIP distance _initial_pos) > 50)) then {
			DM_VIP doMove _initial_pos;
			sleep 3;
			DM_VIP doMove _initial_pos;
		};

		if (DM_Mission_Chapter_CanRun AND _player_detected and !_detected_updated) then {
			_detected_updated = true;
			"You are detected! Reinforcements will surely be called!" call XfMissionMessageToAll;
			_detected_time = time;
		};
		// diag_log Format["(%1)[%2]: %3: %4: en:%5  kill:%6  det:%7  flee:%8",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Loop",_enemy_counts,_dealer_killed,_player_detected,_dealer_fleeing];
		If (DM_Mission_Chapter_CanRun AND _player_detected AND (_reinforcements > 0) AND !_vip_updated) then {
			// If the player is detected and no reinforcement is on the way.. Then we send new troops in :)
			if ((_enemy_initial_counts - _enemy_counts) > _reinforcement_trigger) then {
				if (_unique_id == 0) then {
					// If the reinforcement function returns a value greater than 0, it means a reinforcement was created!
					_unique_id = [d_enemy_side,[_random_town_pos,_random_town_size],"RANDOM",DM_Mission_RandomReinforcement] call XfMissionCallReinforcement;
					if ((_unique_id) > 0) then {
						diag_log Format["(%1)[%2]: %3: %4: reinf:%5, diff:%6, ini:%7, vec:%8",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Sending reinforcement",_reinforcements,_enemy_diff,_enemy_initial_counts];
						_reinforcements = _reinforcements - 1;
						// hint "Reinforcement";
					};
				};
			} else {
				_unique_id = 0;
			};
		};
	};
	
	if (DM_Mission_Mission_CanRun) then {
		if (_chapter_succeeded) then {
			call XfMissionChapterSuccess;
		} else {
			call XfMissionChapterFailure;
		};
	} else {
		diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterExecute","Mission canceled!"];
	};
	
	_players_found = true;
	While {DM_Mission_Mission_CanRun && (([_random_town_pos,(_random_town_size + 200),d_enemy_side] call XfMissionGetZoneSideCount) select 0) > 3 && _players_found} do {
		sleep 5;
		_players_found = false;
		{
			if (([(getPos _x), _random_town_pos, (_random_town_size + 200)] call XfPointInCircle) && isplayer _x) exitWith { _players_found = true; };
		}foreach playableUnits;
	};
	// Just in case a reinforcement is already on the way.
	call XfMissionCancelReinforcement;
	call XfMissionChapterCleanUp;
	DM_Mission_Chapter_Runs = False;
};

XfMissionChapterSetup={
	private ["_gvozdno","_random_town_pos","_random_town_size","_troops_power","_troops_coeff","_grpSoldiers","_grpVehicle","_i"];
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Starting Initialization"];

	// We take towns AND villages
	_random_town = [true] call XfMissionGetRandomTown;
	_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
	if ((count _random_town) <= 0) exitWith {"Could not pick a random town" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	while { (count _random_town > 0) && ((_random_town_pos distance FLAG_BASE) < 700)} do {
		_random_town = [true] call XfMissionGetRandomTown;
		_random_town_pos = _random_town select XF_MAP_LOCATION_CENTER;
	};
	if ((count _random_town) <= 0) exitWith {"Could not pick a random town" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	
	DM_Chapter_Position = _random_town_pos;
	DM_Chapter_Location = _random_town;
	_random_town_size = _random_town select XF_MAP_LOCATION_SIZE;
	_random_town_name = _random_town select XF_MAP_LOCATION_DISPLAYNAME;
	diag_log Format["(%1)[%2]: %3: %4 %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Selected Town:",_random_town];
	
	// We search a spot to place the teleporter which is around the town on a road (to avoid mountains and forests)
	_teleporter = [_random_town_pos] call XfMissionRandomStartTeleporter;
	// If no spot found, we get back an empty position.
	if (count (_teleporter select 0) > 0) then {
		[false,["chapter1_start_position",(_teleporter select 0), "ICON", "ColorBlue", [1,1],"",(_teleporter select 1),"hd_start","",1]] call XfMissionMarker;
	};
	
	// upsmon zone
	[true,["chapter1_random_town_zone", _random_town_pos, "ELLIPSE", "ColorRed", [_random_town_size * 1.5,_random_town_size * 1.5],"",0,"","BDiagonal",0.5]] call XfMissionMarker;
	// target zone
	[false,["chapter1_town_zone", _random_town_pos, "ELLIPSE", "ColorRed", [_random_town_size,_random_town_size],"",0,"","BDiagonal",0.5]] call XfMissionMarker;
	[false,["chapter1_random_town_position",_random_town_pos, "ICON", "ColorRed", [1,1],"The Commander",20,"hd_destroy","",0.6]] call XfMissionMarker;

	// This indicates where the mission takes place
	[_random_town_pos,_random_town_size,_random_town_name] call XfMissionCurrentPosition;

	["jip_vip_found",false] call XNetSetJIP;
	["jip_vip_alive",true] call XNetSetJIP;
	["jip_vip_lead",false] call XNetSetJIP;
	
	_players = call XPlayersNumber;
	_troops_power = 1;
	_troops_coeff = 0;
	switch (true) do {
		case (_players <= 5): { _troops_power = 1 };
		case (_players <= 10): { _troops_power = 1 };
		case (_players <= 15): { _troops_power = 2 };
		case (_players <= 20): { _troops_power = 2 };
		default {_troops_power = 3;};
	};
	if (!isnil "DM_Mission_EnemyPower") then { _troops_power = _troops_power + DM_Mission_EnemyPower; };
	if (!isnil "DM_Mission_EnemyCoeff") then { _troops_coeff = _troops_coeff + DM_Mission_EnemyCoeff; };
	
	diag_log Format["(%1)[%2]: %3:  power:%4  coeff:%5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup",_troops_power,_troops_coeff];

	_i_size = 3;
	_main_bunker_pos = [];
	while { ((count _main_bunker_pos) <= 0) && (_i_size >= 1) } do {
		_main_bunker_pos = [_random_town_pos,(_random_town_size / _i_size),"WarfareBDepot"] call  XfMissionRanObjectivePos;
		_i_size = _i_size - 0.25;
	};
	["WarfareBDepot",_main_bunker_pos,"REGISTER",[],"","NONE"] call XfMissionCreateMissionObject;
	if ((count _main_bunker_pos) < 3) then {
	
	};
	_i_grp_count = 0;
	_bunker_positions = [_main_bunker_pos];
	for [{_i = 0},{_i < 3}, {_i = _i + 1}] do {
		// TODO: Check for roads in the outside boundary of the town
		_i_tries = 30;
		_road_bunker_pos = [];
		_max_size = _random_town_size;
		if (_i_size >= 1) then { _max_size = 1.2 * _max_size; };
		_bunker_distance = _max_size / 4;
		_random_point = [];
		while { ((count _road_bunker_pos) <= 0) && (_i_tries >= 0) } do {
			_random_point = [_random_town_pos, _max_size, _random_town_size / _i_size] call XfGetRanPointCircle;
			if (count _random_point > 0) then {
				if (count (_random_point nearRoads 30) <= 0) then { _random_point = []; };
				if ((count _random_points) == 3) then {
					{
						if ((_random_point distance _x) < _bunker_distance) exitWith {_random_point = [];};
					} foreach _bunker_positions;
				};
			};
			_i_tries = _i_tries - 1;
		};
		if ((count _random_point) > 0) then {
			diag_log Format["(%1)[%2]: %3:  %4  %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Found Road Position",_random_point];
			_i_tries = 25;
			while { ((count _road_bunker_pos) <= 0) && (_i_tries >= 0) } do {
				_road_bunker_pos = [_random_point,30,"Land_Fort_Watchtower"] call  XfMissionRanObjectivePos;
				_i_tries = _i_tries - 1;
			};
			if ((count _road_bunker_pos) > 0) then {
				diag_log Format["(%1)[%2]: %3:  %4  %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Found Bunker Position",_road_bunker_pos];
				_dir = 0;
				_roads = _random_point nearRoads 30;
				if (count _roads > 0) then {
					_road_pos = getPos (_roads call XfRandomArrayVal);
					_dir = [_road_bunker_pos, _road_pos] call XfDirTo;
				};
				["Land_Fort_Watchtower",[_road_bunker_pos, _dir],"REGISTER",[],"","NONE"] call XfMissionCreateMissionObject;
				_grpSoldiers = [d_enemy_side,[_road_bunker_pos,0],["chapter1_random_town_zone","noveh","careless","buildings","nomove"],floor(random(5))] call XfMissionCreateFootmenGroup;
				_i_grp_count = _i_grp_count + 1;
				_bunker_positions set [ count _bunker_positions, _road_bunker_pos];
				sleep 1;
			};		
		};
	};

	_bunker_pos_hiding = ([_main_bunker_pos,10,"INSIDE"] call XfMissionBuildingAreaPosASL) select 0;
	diag_log Format["(%1)[%2]: %3:  %4  %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","VIP Position",_bunker_pos_hiding];
	if ((isnil "_bunker_pos_hiding")) exitWith {"Could not place the VIP" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	if ((count _bunker_pos_hiding) < 3) exitWith {"Could not place the VIP" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	_grp = [d_enemy_side] call x_creategroup;
	_grpSoldiers = [_grp,[_main_bunker_pos,20],["chapter1_random_town_zone","noveh","aware","fortify"],1] call XfMissionCreateFootmenGroup;
	_grp = [d_enemy_side] call x_creategroup;
	_officer_type = ["EAST",[XF_MISSION_CHAR_MILITARY_OFFICER]] call XfMissionGetCharacter;
	DM_VIP = [_officer_type,_grp,[_bunker_pos_hiding,20],"ARREST",["You caught the commander, congratulations!","Damn, you killed the commander....","jip_vip_found","jip_vip_alive"],"doStop this; this setRank ""COLONEL"";"] call XfMissionCreateMissionUnit;
	if (isnull DM_VIP) exitWith {"Could not create the VIP" call XfMissionMessageToAll; DM_Mission_Mission_CanRun = false; DM_Mission_Chapter_CanRun = false;};
	[DM_VIP] joinSilent _grpSoldiers;
	_grpSoldiers selectLeader DM_VIP;
	DM_VIP setVariable ["zeu_AIBypass", true];
	DM_VIP setVariable ["asr_ai_sys_aiskill_exclude", true];
	DM_VIP disableAI "FSM";
	DM_VIP setPosASL _bunker_pos_hiding;
	(group DM_VIP) selectLeader DM_VIP;
	doStop DM_VIP;
	
	for [{_i = _i_grp_count},{_i < 5},{_i = _i + 1}] do {
		_grpSoldiers = [d_enemy_side,[_random_town_pos,_random_town_size],["chapter1_random_town_zone","noveh","careless","buildings"],floor(random(5))] call XfMissionCreateFootmenGroup;
		_i_grp_count = _i_grp_count + 1;
	};
	diag_log Format["(%1)[%2]: %3: %4: %5",diag_tickTime,"chapter1.sqf","XfMissionChapterSetup","Created Groups",_i_grp_count];
	
	if (_troops_power > 1) then {
		// vodnik type
		_grpVehicle = [d_enemy_side,[_main_bunker_pos,(_random_town_size / 2)],["chapter1_random_town_zone","onroad"],4] call XfMissionCreateVehicleGroup;
	} else {
	// UAZ type
		_grpVehicle = [d_enemy_side,[_main_bunker_pos,(_random_town_size / 2)],["chapter1_random_town_zone"],5] call XfMissionCreateVehicleGroup;
	};
	
	// From 10 players, we spawn more troops
	If (_troops_power > 1) then {
		for [{_i=0},{_i< (_troops_power + _troops_coeff) },{_i = _i+1}] do {
			_grpSoldiers = [d_enemy_side,[_random_town_pos,_random_town_size],["chapter1_random_town_zone","noveh","aware","buildings"],floor(random(5))] call XfMissionCreateFootmenGroup;
		};
	};
	
	// We spawn more vehicles as there are players. And from 10 players, we spawn lightly armored vehicles.
	_troops_power = _troops_power * 2;
	for [{_i=0},{_i< (_troops_power + _troops_coeff)},{_i = _i+1}] do {
		_type = 5;
		if ((_troops_power > 1) && (random(1) > 0.7)) then { _type = floor(random 4) + 1; };
		_grpVehicle = [d_enemy_side,[_random_town_pos,_random_town_size*2],["chapter1_random_town_zone"],_type] call XfMissionCreateVehicleGroup;
	};

	["ArrestCommander","Arrest the Commander", "We want the commander alive!<br />He will be judged for the crimes he commited on the cover of the war. Also, he has very valuable informations regarding the reinforcements of our enemy.<br />So be careful not to shoot him down by mistake!<br />We count on you!","",[],"Created"] call XfMissionTask;

	// The trigger which will send reinforcement when the player is detected!
	["jip_player_detected",false] call XNetSetJIP;
	[_random_town_pos,600,d_own_side,d_enemy_side,"jip_player_detected"] call XfMissionSideDetected;

	// We always increase the minimum number of snipers here.
	If (typename DM_Mission_Snipers == "ARRAY") then {
		_min = DM_Mission_Snipers select 0;
		_max = DM_Mission_Snipers select 1;
		if (_min < 2) then { _min = 2;};
		if (_max < _min) then { _max = _min; };
		DM_Mission_Snipers = [_min, _max];
	} else {
		_min = DM_Mission_Snipers;
		_max = DM_Mission_Snipers;
		if (_min < 2) then { _min = 2;};
		if (_max < _min) then { _max = _min; };
		DM_Mission_Snipers = [_min, _max];
	};
	// This will create snipers automatically if selected in the mission setup
	[d_enemy_side,[_random_town_pos,_random_town_size],DM_Mission_Snipers] call XfMissionCreateSnipersArea;
	// This will create air support automatically if selected in the mission setup
	[d_enemy_side,[_random_town_pos,_random_town_size],DM_Mission_AirSupport] call XfMissionCallAirSupport;
};

XfMissionChapterSuccess={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterSuccess","Starting"];
	"Congratulations! The information he can provide will be very helpful!" call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = 1;
};

XfMissionChapterFailure={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterFailure","Starting"];
	"You tried but failed... you'll do better next time." call XfMissionMessageToAll;
	DM_Mission_Chapter_Success = -1;
};

// Self-explanatory
XfMissionChapterCleanUp={
	diag_log Format["(%1)[%2]: %3; %4",diag_tickTime,"chapter1.sqf","XfMissionChapterCleanUp","Starting"];
	// Giving an empty position places the teleporter back to the hangar, closing the hangar.
	[[],0] call XfMissionPlaceStartTeleporter;
	[] call XfMissionCleanMarkers;
	[] call XfMissionCleanTriggers;
	[] call XfMissionCleanTasks;
};

DM_Mission_Chapter_Compiled = true;